using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.Xml.Serialization;

namespace MazeWars
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        KeyboardState currState;
        GamePadState currPadState;
        bool saveRequest;
        IAsyncResult result;

        /// <summary>
        /// Data structure containing all variables that are writen to a save file.
        /// </summary>
        [Serializable]
        public struct SaveGameData
        {
            public string name;
            public int level;
        }

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            saveRequest = false;

            Components.Add(new GamerServicesComponent(this));

        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            WindowManager.instance().loadWindowContent(Content, GraphicsDevice.Viewport);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
            SoundManager.Instance().Shutdown();
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            KeyboardState prevState = currState;
            currState = Keyboard.GetState();
            GamePadState prevPadState = currPadState;
            currPadState = GamePad.GetState(PlayerIndex.One);
            // Allows the game to exit
#if XBOX
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
#endif

            if (currState.IsKeyDown(Keys.Escape))
                this.Exit();
            // TODO: Add your update logic here

            //This is for XBOX only------------------------------------------------------------------------------
#if XBOX
            if (currPadState.Buttons.B == ButtonState.Pressed && prevPadState.Buttons.B == ButtonState.Released)
            {
                if (!Guide.IsVisible && saveRequest == false)
                {
                    saveRequest = true;
                    result = Guide.BeginShowStorageDeviceSelector(PlayerIndex.One, null, null);
                }
            }

            if (saveRequest && result.IsCompleted)
            {
                StorageDevice device = Guide.EndShowStorageDeviceSelector(result);
                if (device != null && device.IsConnected)
                {
                    //Function for saving game.
                    DoSaveGame(device);
                }
            }
#endif
            //-----------------------------------------------------------------------------------------------------

            //For audio/XACT
            SoundManager.Instance().Update();

            WindowManager.instance().getActiveWindow().update(currState, gameTime);

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            WindowManager.instance().getActiveWindow().draw(spriteBatch, GraphicsDevice);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }

        /// <summary>
        /// Creates a file if it does not already exist in the Storage Device.
        /// </summary>
        /// <param name="device">Storage Device containing the container the file will reside in</param>
        private static void DoCreate(StorageDevice device)
        {
            StorageContainer container = device.OpenContainer("SaveGame");

            string filename = Path.Combine(container.Path, "saveGame.sav");

            if (!File.Exists(filename))
            {
                FileStream file = File.Create(filename);
                file.Close();
            }

            container.Dispose();
        }

        /// <summary>
        /// Opens a file in the Storage Device
        /// </summary>
        /// <param name="device">Storage Device containing the container the file will reside in</param>
        private static void DoOpen(StorageDevice device)
        {
            StorageContainer container = device.OpenContainer("SaveGame");

            string filename = Path.Combine(container.Path, "saveGame.sav");

            FileStream file = File.Open(filename, FileMode.Open);
            
            file.Close();

            container.Dispose();
        }

        private static void DoOpenFile()
        {
            FileStream file = OpenTitleFile("filename.dds", FileMode.Open, FileAccess.Read);

            file.Close();
        }

        private static FileStream OpenTitleFile(string filename, FileMode mode, FileAccess access)
        {
            string fullpath = Path.Combine(StorageContainer.TitleLocation, filename);
            return File.Open(fullpath, mode, access);
        }

        private static void DoSaveGame(StorageDevice device)
        {
            SaveGameData data = new SaveGameData();
            data.name = "Bob";
            data.level = 3;

            StorageContainer container = device.OpenContainer("SaveGame");
            string filename = Path.Combine(container.Path, "savegame.sav");
            FileStream stream = File.Open(filename, FileMode.Create);

            XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
            serializer.Serialize(stream, data);

            stream.Close();

            container.Dispose();
        }

        private static void DoLoadGame(StorageDevice device)
        {
            SaveGameData data;

            StorageContainer container = device.OpenContainer("SavaGame");
            string filename = Path.Combine(container.Path, "savegame.sav");
            FileStream stream = File.Open(filename, FileMode.Open);

            XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
            data = (SaveGameData)serializer.Deserialize(stream);

            stream.Close();

            container.Dispose();
        }
    }//End of main
}
